import { derived, writable } from "svelte/store";
import type { DeviceType } from "../../components/Device/type";
import { collegeUrl, getDeviceStatusTrendData, selectAlarmRecordByLocationId, selectDeviceAlarmData, selectDeviceTypeCountData, selectDevicesByLocationId, selectGyDeviceDetail } from "../api";

export interface StatusTrend {
  data: any[],
  catalog: any[]
}

function createStatusTrend() {
  const { subscribe, set, update } = writable<StatusTrend>({ data: [], catalog: [] })

  return {
    subscribe, set, update,
    get: async () => {
      // const response = await fetch('/mock/college/statusTrend.json')
      // const data = await response.json()
      const response = await fetch(getDeviceStatusTrendData)
      const { data } = await response.json()
      set(data)
    },
  }
}

export const statusTrend = createStatusTrend()

const locationMock = [
  { "top": 0, "left": 400 },
  { "top": 0, "left": 150 },
  { "top": 150, "left": 200 },
  { "top": 100, "left": 300 },
  { "top": 0, "left": 20 },
  { "top": 120, "left": 100 },
  { "top": 180, "left": 300 },
  { "top": 130, "left": 200 },
  { "top": 100, "left": 400 },
  { "top": 100, "left": 30 },
  { "top": 100, "left": 90 },
  { "top": 100, "left": 520 },
]

export interface Device {
  id: number
  label: string
  type: string
  location: {
    top: number
    left: number
  }
  filePath?: string
  active: boolean
}

function createDevices() {
  const { subscribe, set, update } = writable<Device[]>([])
  const isDetail = writable<boolean>(false)
  return {
    isDetail,
    subscribe,
    fill: (devices: Device[]) => set(devices),
    get: async (id) => {
      // const response = await fetch('/mock/college/devices.json')
      // const data = await response.json()
      const response = await fetch(`${selectDevicesByLocationId}/${id}`)
      const { data = [] } = await response.json()
      data.forEach((device: Device, index) => {
        if (device.location) {
          device.location = locationMock[index % locationMock.length]
        }
      })
      set(data)
    },
    select: (t: number, id: number, type: string) => {
      update((devices: Device[]) => {
        return devices.map(device => {
          if (device.id === id) {
            device.active = !device.active
            if (device.active) {
              isDetail.set(true)
            } else {
              isDetail.set(false)
            }
          } else {
            device.active = false
          }
          return device
        })
      })
      devicesDetail.get(t, id, type)
    },
  }
}

export const devices = createDevices()

export interface DevicesDetail {

}

function createDevicesDetail() {
  const { subscribe, set, update } = writable<any>({})
  return {
    subscribe, set, update,
    get: async (t, id, type) => {
      console.log(1000, t, id, type)
      // const response = await fetch('/mock/college/details.json')
      // const details = await response.json()
      // const data = details.find(s => +s.id === +id)
      // console.log(details, data)
      const response = await fetch(`${selectGyDeviceDetail}/${t}/${id}`)
      const { data = {} } = await response.json()
      data.type = type
      set(data)
    },
  }
}

export const devicesDetail = createDevicesDetail()

function createClassroom() {
  const index = writable<number>(0)
  const interval = setInterval(function toggle() {
    index.update(i => (i + 1) % 5)
  }, 4000)
  return index
}


export const classroomIndex = createClassroom()

export interface Status {
  id: number,
  normal: number
  warning: number
  error: number
  offline: number
}

function createStatus() {
  const { subscribe, set, update } = writable<Status>({ error: 0, id: 0, normal: 0, offline: 0, warning: 0 })

  return {
    subscribe, set, update,
    get: async (id) => {
      const response = await fetch('/mock/college/status.json')
      const data = await response.json()
      const status = data.find(s => +s.id === +id)
      set(status)
    },
  }
}

export const status = createStatus()

classroomIndex.subscribe(index => {
  // status.get(index + 1)
})

function createCatalog() {
  const { subscribe, set, update } = writable<any>([])

  return {
    subscribe, set, update,
    get: async (id) => {
      // const response = await fetch('/mock/index/catalog.json')
      // const res = await response.json()
      // const status = res.find(s => +s.id === +id)
      // const data = status.data
      // console.log(id, data, status)
      const response = await fetch(selectDeviceTypeCountData)
      const { data = [] } = await response.json()
      set(data)
    },
  }
}

export const catalog = createCatalog()


function createWarning() {
  const { subscribe, set, update } = writable<any>([])

  return {
    subscribe, set, update,
    get: async () => {
      // const response = await fetch('/mock/college/warning.json')
      // const data = await response.json()
      const response = await fetch(selectDeviceAlarmData)
      const { data = [] } = await response.json()
      set(data)
    },
  }
}

export const warning = createWarning()

function createTargets() {
  const { subscribe, set, update } = writable<any>([])

  return {
    subscribe, set, update,
    get: async (id) => {
      // const response = await fetch('/mock/college/targets.json')
      // const data = await response.json()
      const response = await fetch(`${selectDeviceAlarmData}/${id}`)
      const { data = [] } = await response.json()
      set(data)
    },
  }
}

export const targets = createTargets()

export interface Realtime {
  name: string
  type: string
  status: string
  timer: string
}

function createRealtime() {
  const { subscribe, set, update } = writable<Realtime[]>([])

  return {
    subscribe, set, update,
    get: async (id) => {
      // const response = await fetch('/mock/index/realtime.json')
      // const realtime = await response.json()
      const response = await fetch(`${selectAlarmRecordByLocationId}/${id}`)
      const { data = [] } = await response.json()
      set(data)
    },
  }
}

export const realtime = createRealtime()